﻿using Bangle.BLL;
using Bangle.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Account_RoleEdit : BasePage
{
    #region 属性
    /// <summary>
    /// Id
    /// </summary>
    private int Id
    {
        get
        {
            return ViewState["Id"] == null ? 0 : Convert.ToInt32(ViewState["Id"]);
        }
        set
        {
            ViewState["Id"] = value;
        }
    }

    /// <summary>
    /// Action
    /// </summary>
    private string Action
    {
        get
        {
            return ViewState["Action"] == null ? "Add" : ViewState["Action"].ToString();
        }
        set
        {
            ViewState["Action"] = value;
        }
    }
    #endregion

    Sys_Role model = new Sys_Role();
    Sys_RoleBLL bll = new Sys_RoleBLL();
    Sys_OperationTypeBLL operationType_bll = new Sys_OperationTypeBLL();
    Sys_OperationBLL operation_bll = new Sys_OperationBLL();

    CheckBoxList cbl_BaseOperation = new CheckBoxList();

    #region 加载
    protected void Page_Load(object sender, EventArgs e)
    {
        //检验用户权限
        setUserControlStatus();

        if (!IsPostBack)
        {
            Id = base.ParseQueryInt("Id", 0);
            Action = base.ParseQueryString("Action", "Add");

            if (Action == "Modify" || Action == "Detail")
            {
                getDate(Id);
            }
            if (Action == "Detail")
            {
                this.txt_RoleCode.Enabled = false;
                this.txt_RoleName.Enabled = false;
                this.ch_Valid.Enabled = false;

                this.btn_Modify.Visible = true;
                this.btn_Save.Visible = false;
            }
            else if (Action == "Add" || Action == "Modify")
            {
                this.txt_RoleCode.Enabled = true;
                this.txt_RoleName.Enabled = true;
                this.ch_Valid.Enabled = true;

                this.btn_Modify.Visible = false;
                this.btn_Save.Visible = true;
            }

            BindModuleList();
        }
    }
    #endregion

    #region 检验用户权限
    private void setUserControlStatus()
    {
        //检验用户权限
        base.CheckUserPermission("001002");
        this.btn_Modify.Enabled = base.CheckUserPermissionOperation("001002", "Add");
        this.btn_Save.Enabled = base.CheckUserPermissionOperation("001002", "Add") || base.CheckUserPermissionOperation("001002", "Edit");
    }
    #endregion

    #region 绑定数据
    /// <summary>
    /// 加载数据
    /// </summary>
    /// <param name="id"></param>
    private void getDate(int id)
    {
        model = bll.GetModel(id);
        if (model == null)
        {
            return;
        }
        this.txt_RoleCode.Text = model.RoleCode;
        this.txt_RoleName.Text = model.RoleName;
        this.ch_Valid.Checked = model.Valid == 1;
    }
    #endregion

    #region 提交
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        //检验数据是否重复
        string strCheck = string.Format("(RoleName like '{0}' or RoleCode like '{1}') and RoleId<>{2}",
            TextUtility.ReplaceText(this.txt_RoleName.Text.Trim()),
            TextUtility.ReplaceText(this.txt_RoleCode.Text.Trim()),
            Id.ToString());

        if (bll.GetRecordCount(strCheck) > 0)
        {
            base.Alert("模块名称或模块编码已存在！");
            return;
        }

        if (Action == "Modify")
        {
            model = bll.GetModel(Id);
        }
        else if (Action == "Add")
        {
            model = new Sys_Role();
        }
        else
        {
            base.Alert("异常操作！");
            return;
        }

        model.RoleName = this.txt_RoleName.Text.Trim();
        model.RoleCode = this.txt_RoleCode.Text.Trim();
        model.Valid = this.ch_Valid.Checked ? 1 : 0;


        try
        {
            if (Action == "Modify")
            {
                //修改
                bll.Update(model);
            }
            else if (Action == "Add")
            {
                //保存
                Id = bll.Add(model);
            }

            #region 保存操作权限
            for (int i = 0; i < RepeaterList.Items.Count; i++)
            {
                HiddenField hf_ModuleId = (HiddenField)RepeaterList.Items[i].FindControl("hf_ModuleId");
                CheckBoxList cbl_Operation = (CheckBoxList)RepeaterList.Items[i].FindControl("cbl_Operation");
                int moduleid = Convert.ToInt32(hf_ModuleId.Value);

                foreach (ListItem item in cbl_Operation.Items)
                {
                    int operationtypeid = Convert.ToInt32(item.Value);
                    if (item.Selected)
                    {
                        if (operation_bll.GetRecordCount("RoleId=" + Id + " and ModuleId=" + moduleid + " and OperationTypeId=" + item.Value) < 1)
                        {
                            Sys_Operation operation = new Sys_Operation();
                            operation.RoleId = Id;
                            operation.ModuleId = moduleid;
                            operation.OperationTypeId = operationtypeid;
                            operation_bll.Add(operation);
                        }
                    }
                    else
                    {
                        operation_bll.Delete(Id, moduleid, operationtypeid);
                    }
                }
            }
            #endregion

            base.Redirect("操作成功！", "RoleEdit.aspx?Action=Detail&Id=" + Id.ToString());
        }
        catch (Exception ex)
        {
            base.Alert("操作失败！");
        }
    }
    #endregion

    #region 编辑按钮
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        Response.Redirect("RoleEdit.aspx?Action=Modify&Id=" + Id);
    }
    #endregion

    #region 数据绑定

    private void BindModuleList()
    {
        //给操作类型动态添加CheckBoxList 项
        List<Sys_OperationType> typeList = new List<Sys_OperationType>();
        typeList = operationType_bll.GetModelList("Valid=1");
        foreach (var item in typeList)
        {
            cbl_BaseOperation.Items.Add(new ListItem(item.OperationTypeName, item.OperationTypeId.ToString()));
        }

        //绑定Repeater
        UtilityBLL ubll = new UtilityBLL();
        int rCount = 0;
        string sWhere = "Valid=1 and ParentId>0";
        if (base.CurrentSession.LoginName != "root")
        {
            sWhere += " and ModuleCode<>'001001'";
        }

        DataTable dt = ubll.GetListByPage("View_Module", "*", "SysNo desc,ParentId,OrderNo", sWhere, 10000, 1, 0, out rCount);
        RepeaterList.DataSource = dt;
        RepeaterList.DataBind();
    }
    #endregion

    #region 列表操作
    protected void RepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int moduleid = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "ModuleId"));
            CheckBoxList cbl_Operation = (CheckBoxList)e.Item.FindControl("cbl_Operation");
            for (int i = 0; i < cbl_BaseOperation.Items.Count; i++)
            {
                ListItem item = new ListItem(cbl_BaseOperation.Items[i].Text, cbl_BaseOperation.Items[i].Value);

                if (operation_bll.GetRecordCount("RoleId=" + Id + " and ModuleId=" + moduleid + " and OperationTypeId=" + item.Value) > 0)
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }
                item.Attributes.CssStyle.Add(HtmlTextWriterStyle.MarginRight, "10px");

                cbl_Operation.Items.Add(item);
            }
            cbl_Operation.Enabled = (Action == "Add" || Action == "Modify");
        }
    }
    #endregion
}